package com.travel.service;

import java.awt.Font;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.PiePlot;
import org.jfree.data.general.DefaultPieDataset;

import com.travel.core.DaoFactory;
import com.travel.dao.ISpotDao;

public class DrawPie {
	private String SpotName = "桂林市";
	private List<String> years;
	private ChartPanel frame1;
	private String cityCode = "0773";
	private int selectedType = 2;
	private static final ISpotDao SPOT_DAO = DaoFactory.getDao(ISpotDao.class);

	public DrawPie(String cityCode, String spotName, List<String> years, int selectedType) {
		this.cityCode = cityCode;
		this.SpotName = spotName;
		this.years = years;
		this.selectedType = selectedType;
		yearSpotPie();
	}

	public JFreeChart yearSpotPie() {
		DefaultPieDataset data = getDataSet();
		JFreeChart chart = ChartFactory.createPieChart3D(SpotName + years.get(0) + "年游客流量季度分析", data, true, false,
				false);
		// 设置百分比
		PiePlot pieplot = (PiePlot) chart.getPlot();
		DecimalFormat df = new DecimalFormat("0.00%");// 获得一个DecimalFormat对象，主要是设置小数问题
		NumberFormat nf = NumberFormat.getNumberInstance();// 获得一个NumberFormat对象
		StandardPieSectionLabelGenerator sp1 = new StandardPieSectionLabelGenerator("{0}  {2}", nf, df);// 获得StandardPieSectionLabelGenerator对象
		pieplot.setLabelGenerator(sp1);// 设置饼图显示百分比

		// 没有数据的时候显示的内容
		pieplot.setNoDataMessage("无数据显示");
		pieplot.setCircular(false);
		pieplot.setLabelGap(0.02D);

		pieplot.setIgnoreNullValues(true);// 设置不显示空值
		pieplot.setIgnoreZeroValues(true);// 设置不显示负值
		frame1 = new ChartPanel(chart, true);
		chart.getTitle().setFont(new Font("宋体", Font.BOLD, 20));// 设置标题字体
		PiePlot piePlot = (PiePlot) chart.getPlot();// 获取图表区域对象
		piePlot.setLabelFont(new Font("宋体", Font.BOLD, 15));// 解决乱码
		chart.getLegend().setItemFont(new Font("黑体", Font.BOLD, 10));
		return chart;
	}

	private DefaultPieDataset getDataSet() {
		DefaultPieDataset dataset = new DefaultPieDataset();
		double value1 = 0;
		double value2 = 0;
		double value3 = 0;
		double value4 = 0;
		List<Map<String, Object>> yearCount = SPOT_DAO.getStaticticsByCityOrSpotYear(cityCode,
				Arrays.asList(years.get(0)), selectedType);
		int i = 1;
		for (Map<String, Object> ymMap : yearCount) {
			int val = Integer.parseInt(ymMap.get("count").toString());
			if (i >= 1 && i <= 3) {
				value1 += val;
			}
			if (i >= 4 && i <= 6) {
				value2 += val;
			}
			if (i >= 7 && i <= 9) {
				value3 += val;
			}
			if (i >= 10 && i <= 12) {
				value4 += val;
			}
			i++;
		}

		dataset.setValue("一季度", value1);
		dataset.setValue("二季度", value2);
		dataset.setValue("三季度", value3);
		dataset.setValue("四季度", value4);
		return dataset;
	}

	public ChartPanel getChartPanel() {
		return frame1;
	}
}
